/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-10-31 11:22:32
 * @LastEditTime : 2024-02-04 14:10:54
 */
import { ComponentEntity } from './../entity/component';
import { Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
import { buildUUID } from '../../../comm/uuid';
@Provide()
export class ComponentService extends BaseService {
  @InjectEntityModel(ComponentEntity)
  componentEntity: Repository<ComponentEntity>;

  async queryComsByProjectId(screenId: any) {
    const result = await this.componentEntity.findBy({ screenId });
    if (!result) return null;
    return result.map(v => {
      return {
        ...v,
        actions: JSON.parse(v.actions || '{}'),
        apiData: JSON.parse(v.apiData),
        apis: JSON.parse(v.apis),
        attr: JSON.parse(v.attr),
        config: JSON.parse(v.config),
        events: JSON.parse(v.events),
        children: JSON.parse(v.children),
        scaling: JSON.parse(v.scaling),
        animate: JSON.parse(v.animate),
        bgImg: JSON.parse(v.bgImg || '{}'),
        dialog: JSON.parse(v.dialog || '{}'),
        disActions: JSON.parse(v.disActions || '[]'),
      };
    });
  }

  async addComponents(coms) {
    const comArr = coms.map(com => {
      return {
        ...com,
        attr: JSON.stringify(com.attr),
        config: JSON.stringify(com.config),
        apis: JSON.stringify(com.apis),
        events: JSON.stringify(com.events),
        scaling: JSON.stringify(com.scaling),
        apiData: JSON.stringify(com.apiData),
        children: JSON.stringify(com.children),
        animate: JSON.stringify(com.animate || {}),
        bgImg: JSON.stringify(com.bgImg),
        dialog: JSON.stringify(com.dialog || {}),
        disActions: JSON.stringify(com.disActions || []),
        actions: JSON.stringify(com.actions || {}),
      };
    });
    const res = await this.componentEntity.insert(comArr);
    return res?.identifiers || null;
  }

  async deleteComponents(ids) {
    const idsArr = ids.split(',');
    const res = await this.componentEntity.delete({
      id: In(idsArr),
    });
    await this.componentEntity.delete({
      parentId: In(idsArr),
    });
    return res;
  }

  // 批量更新组件
  async updateComponents(coms) {
    const promiseArr = [];
    coms.forEach(com => {
      promiseArr.push(
        this.componentEntity.update(
          {
            id: com.id,
          },
          {
            sortOrder: com.sortOrder,
            screenId: com.screenId,
            type: com.type,
            alias: com.alias,
            name: com.name,
            locked: com.locked,
            hided: com.hided,
            icon: com.icon,
            img: com.img,
            parentId: com.parentId,
            selected: com.selected,
            hovered: com.hovered,
            bgAnimation: com.bgAnimation,
            children: JSON.stringify(com.children),
            apiData: JSON.stringify(com.apiData),
            apis: JSON.stringify(com.apis),
            attr: JSON.stringify(com.attr),
            config: JSON.stringify(com.config),
            events: JSON.stringify(com.events),
            scaling: JSON.stringify(com.scaling),
            animate: JSON.stringify(com.animate || {}),
            bgImg: JSON.stringify(com.bgImg),
            dialog: JSON.stringify(com.dialog || {}),
            actions: JSON.stringify(com.actions || {}),
            isDialog: com.isDialog,
            disActions: JSON.stringify(com.disActions || []),
          } as any
        )
      );
    });

    return await Promise.all(promiseArr);
  }

  async copyComponents(ids) {
    const queryIds = ids
      .split(',')
      .map(item => `'${item.trim()}'`)
      .join(', ');
    const coms = await this.componentEntity.find({
      where: {
        id: In(queryIds),
      } as any,
    });
    const addArr: any[] = [];
    coms.forEach(com => {
      addArr.push(
        this.componentEntity.save({
          ...com,
          id: `${com.id.split('_')[0]}_${buildUUID()}`,
        })
      );
    });
    const res = await Promise.all(addArr);
    return res;
  }

  async deleteComponentByScreen(id) {
    const res = await this.componentEntity.delete({
      screenId: id,
    });
    return res;
  }
}
